import { PageContainer, ProColumns } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Button, Card, Col, Flex, Image, message, Row, Select, Tag, Typography } from 'antd';
import { useParams } from '@@/exports';
import { useModel } from '@umijs/max';
import {
  deletePictureUsingPost,
  getPictureVoByIdUsingGet,
} from '@/services/backend/pictureController';
import { DeleteOutlined, DownloadOutlined, EditOutlined } from '@ant-design/icons';
import { downloadImage } from '@/utils';
import { formatToSuffixMap } from '@/constants/picture';
import UpdatePictureModal from '@/components/UpdatePictureModal';
import usePictureTagCategory from '@/hooks/usePictureTagCategory';

const { Title, Paragraph } = Typography;

const IndexPage: React.FC = () => {
  const { id } = useParams();
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<API.PictureVO>({});
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const my = currentUser?.id === data?.userId;
  const [updatePictureModalVisible, setUpdatePictureModalVisible] = useState<boolean>(false);
  const { tagList, categoryList } = usePictureTagCategory();
  /**
   * 表格列配置
   */
  const pictureColumns: ProColumns<API.PictureVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '图片',
      hideInSearch: true,
      dataIndex: 'url',
      valueType: 'image',
      renderFormItem(_, record) {
        return (
          <div
            style={{
              display: 'flex',
              flexDirection: 'column', // 垂直排列
              justifyContent: 'center', // 垂直居中
              alignItems: 'center', // 水平居中
              gap: 10,
            }}
          >
            <Image src={record.value} alt={record.value} width={100} height={100} />
          </div>
        );
      },
    },
    {
      title: '图片名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '分类',
      dataIndex: 'category',
      valueType: 'text',
      renderFormItem(schema) {
        const { fieldProps } = schema;

        //@ts-ignore
        return (
          <Select
            options={categoryList?.map((item) => {
              return {
                label: item,
                value: item,
              };
            })}
            {...fieldProps}
          />
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      renderFormItem(schema) {
        const { fieldProps } = schema;
        //@ts-ignore
        return (
          <Select
            options={tagList?.map((item) => {
              return {
                label: item,
                value: item,
              };
            })}
            {...fieldProps}
            mode="tags"
          />
        );
      },
      render(_, record) {
        if (!record.tags) {
          return <></>;
        }
        return record.tags.map((tag) => {
          return (
            <Tag style={{ marginBottom: 10 }} key={tag}>
              {tag}
            </Tag>
          );
        });
      },
    },
    {
      title: '简介',
      dataIndex: 'introduction',
      valueType: 'textarea',
      ellipsis: true,
    },
  ];

  function getImageSuffix(format: string) {
    // 将格式转换为小写，避免大写和小写问题
    const lowerCaseFormat = format.toLowerCase();

    // 查找映射中的后缀，如果找不到则返回默认值（如：'unknown'）
    return formatToSuffixMap[lowerCaseFormat] || 'unknown';
  }

  const loadData = async () => {
    if (!id) {
      return;
    }
    setLoading(true);
    try {
      const res = await getPictureVoByIdUsingGet({
        id: id,
      });
      setData(res.data ?? {});
    } catch (e: any) {
      message.error('获取失败:' + e.message);
    }
    setLoading(false);
  };
  const tagListView = (tags: string[]) => {
    if (!tags) return;
    return tags.map((item, index) => <Tag key={index}>{item}</Tag>);
  };
  useEffect(() => {
    if (!id) {
      return;
    }
    loadData();
  }, [id]);
  const handleDelete = async (row: API.PictureVO) => {
    const hide = message.loading('正在删除');
    const ids: string[] = [row.id as any];
    const batchDeleteRequest: API.BatchDeleteRequest = {
      ids,
    };
    if (!row) return true;
    try {
      await deletePictureUsingPost(batchDeleteRequest);
      hide();
      message.success('删除成功');
      window.location.href = '/index';
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };
  return (
    <PageContainer breadcrumbRender={false} title={<></>}>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={18}>
            <Image src={data.url} />
            <div style={{ marginTop: 24 }} />
            <Flex flex="column" justify="flex-start">
              <Flex>{data.category && <Tag color="green">{data.category}</Tag>}</Flex>
              <Flex style={{ overflow: 'hidden' }}>{tagListView(data?.tags ?? [])}</Flex>
            </Flex>
          </Col>
          <Col span={6} style={{ marginBottom: '16px', padding: '8px', borderRadius: '4px' }}>
            <Card style={{ display: 'flex' }}>
              <Row gutter={[16, 8]}>
                <Col span={24}>
                  <Title level={5}>图片名称：{data.name}</Title>
                </Col>
                <Col span={24}>
                  <Paragraph type="secondary">图片描述：{data.introduction}</Paragraph>
                </Col>
                <Col span={24}>
                  <Row gutter={[16, 8]} align="middle">
                    <Col span={18}>
                      <Paragraph type="secondary">上传者：{data.user?.userName}</Paragraph>
                    </Col>
                    <Col span={6}>
                      <Image
                        src={data.user?.userAvatar}
                        preview={false}
                        width={40}
                        height={40}
                        style={{ borderRadius: '50%' }}
                      />
                    </Col>
                  </Row>
                </Col>
              </Row>
              <div style={{ flexGrow: 1 }} />
              <Row gutter={[8, 8]} justify="center" style={{ marginTop: '16px' }}>
                <Col span={24}>
                  <Button
                    type="primary"
                    icon={<DownloadOutlined />}
                    block
                    onClick={() => {
                      if (!data.picFormat) {
                        return;
                      }
                      const suffix = getImageSuffix(data.picFormat);
                      downloadImage(data.url, data.name + '.' + suffix);
                    }} // 调用下载函数
                  >
                    免费下载
                  </Button>
                </Col>
              </Row>
              {(my || 'admin' === currentUser?.userRole) && (
                <>
                  <Row gutter={[8, 8]} justify="center" style={{ marginTop: '16px' }}>
                    <Col span={24}>
                      <Button
                        type="default"
                        icon={<EditOutlined />}
                        block
                        onClick={() => {
                          setUpdatePictureModalVisible(true);
                        }}
                      >
                        编辑
                      </Button>
                    </Col>
                  </Row>
                  <Row gutter={[8, 8]} justify="center" style={{ marginTop: '16px' }}>
                    <Col span={24}>
                      <Button
                        type={'primary'}
                        danger
                        icon={<DeleteOutlined />}
                        block
                        onClick={() => {
                          handleDelete(data);
                        }} // 调用下载函数
                      >
                        删除
                      </Button>
                    </Col>
                  </Row>
                </>
              )}
            </Card>
          </Col>
        </Row>
      </Card>
      <UpdatePictureModal
        oldData={data}
        visible={updatePictureModalVisible}
        columns={pictureColumns}
        onSubmit={async () => {
          await loadData();
          setUpdatePictureModalVisible(false);
        }}
        onCancel={() => {
          setUpdatePictureModalVisible(false);
        }}
      />
    </PageContainer>
  );
};

export default IndexPage;
